package edu.fdzc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.fdzc.exception.BusinessException;
import edu.fdzc.mapper.ClazzMapper;
import edu.fdzc.pojo.*;
import edu.fdzc.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public List<Clazz> getAllClazz() {
        return clazzMapper.getAllClazz();
    }

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //1. 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        //2. 执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        Page<Clazz> p = (Page<Clazz>) clazzList;

        //3. 添加状态判断逻辑
        LocalDateTime now = LocalDateTime.now();
        for (Clazz clazz : clazzList) {
            if (now.isAfter(clazz.getEndDate().atStartOfDay())) {
                clazz.setStatus("已结课");
            } else if (now.isBefore(clazz.getBeginDate().atStartOfDay())) {
                clazz.setStatus("未开班");
            } else {
                clazz.setStatus("在读中");
            }
        }

        //4. 封装结果
        return new PageResult<Clazz>(p.getTotal(), p.getResult());

    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Transactional
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(clazz.getEndDate().atStartOfDay())) {
            clazz.setStatus("已结课");
        } else if (now.isBefore(clazz.getBeginDate().atStartOfDay())) {
            clazz.setStatus("未开班");
        } else {
            clazz.setStatus("在读中");
        }
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        // 查询该班级是否有学生
        int studentCount = clazzMapper.countStudentsByClazzId(id);
        if (studentCount > 0) {
            throw new BusinessException("该班级下存在学生，无法删除");
        }
        clazzMapper.deleteById(id);
    }
}
